<script setup lang="ts">
import { ref, computed, onMounted, h, watch } from 'vue'
import {
  Button,
  Card,
  Table,
  Modal,
  Form,
  Input,
  message,
  Tree,
  Space,
  Spin,
  Tag,
  Select
} from 'ant-design-vue'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  BankOutlined,
  BookOutlined,
  TeamOutlined,
  SearchOutlined,
  ReloadOutlined,
  KeyOutlined
} from '@ant-design/icons-vue'
import type { Organization } from '@/types/organization'
import { organizationApi } from '@/api/modules/organization'
import { studentApi } from '@/api/modules/student'
import type { TableColumnsType } from 'ant-design-vue'
import type { Key } from 'ant-design-vue/es/table/interface'
import type { Student } from '@/types/student'
import dayjs from 'dayjs' // 确保项目中已安装 dayjs

// 组织类型定义
const organizationType = {
  COLLEGE: 1,
  MAJOR: 2,
  CLASS: 3
} as const

// 页面加载状态
const loading = ref(false)
const treeLoading = ref(false)

// 组织树数据
const treeData = ref<Organization[]>([])
const selectedNode = ref<any>(null)

// 表格数据
const tableData = ref<Student[]>([])
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: (total: number) => `共 ${total} 条记录`,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '30', '50'],
  // 自定义页码选项的文本
  buildOptionText: (opt: { value: number }) => {
    return `${opt.value} 条/页`
  }
})

// 性别选项
const genderOptions = [
  { label: '未知', value: 0 },
  { label: '男', value: 1 },
  { label: '女', value: 2 }
]

// 表单数据
interface StudentForm {
  id?: number
  realName: string
  userCode: string
  gender: number
  phone?: string
  email?: string
  departmentId: number
}

const formRef = ref()
const formState = ref<StudentForm>({
  realName: '',
  userCode: '',
  gender: 0, // 默认未知
  phone: '',
  email: '',
  departmentId: 0
})

// 弹窗控制
const modalVisible = ref(false)
const modalTitle = ref('新增学生')
const modalLoading = ref(false)

// 添加搜索表单接口
interface SearchForm {
  studentNo?: string
  name?: string
}

// 添加搜索表单状态
const searchForm = ref<SearchForm>({})

// 转换树形数据
const treeNodes = computed(() => {
  const convert = (items: Organization[]): any[] => {
    if (!items?.length) return []
    return items.map(item => ({
      key: item.id,
      title: item.name,
      type: item.type,
      icon: () => {
        switch (item.type) {
          case organizationType.COLLEGE:
            return h(BankOutlined, { style: { color: '#1890ff' } })
          case organizationType.MAJOR:
            return h(BookOutlined, { style: { color: '#52c41a' } })
          case organizationType.CLASS:
            return h(TeamOutlined, { style: { color: '#faad14' } })
          default:
            return null
        }
      },
      children: item.children ? convert(item.children) : undefined,
      isLeaf: item.type === organizationType.CLASS
    }))
  }
  return convert(treeData.value)
})

// 表格列配置
const columns: TableColumnsType = [
  {
    title: '学号',
    dataIndex: 'username',
    width: 120,
    align: 'center'
  },
  {
    title: '姓名',
    dataIndex: 'realName',
    width: 120,
    align: 'center'
  },
  {
    title: '性别',
    dataIndex: 'gender',
    width: 80,
    align: 'center',
    customRender: ({ text }) => {
      const gender = genderOptions.find(item => item.value === text)
      return gender ? gender.label : '未知'
    }
  },
  {
    title: '班级',
    dataIndex: 'departmentName',
    width: 180,
    align: 'center',
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    width: 150,
    align: 'center'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100,
    align: 'center',
    key: 'status',
    customRender: ({ text, record }) => h(Tag, {
      color: text ? 'success' : 'error',
      style: { cursor: 'pointer' },
      onClick: () => handleStatusChange(record)
    }, {
      default: () => text ? '启用' : '禁用'
    })
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
    align: 'center',
    customRender: ({ text }) => {
      return text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '-'
    }
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    align: 'center',
    fixed: 'right',
    slots: { customRender: 'action' }
  }
]

// 获取组织树数据
const getOrganizationTree = async () => {
  treeLoading.value = true
  try {
    const data = await organizationApi.getTree()
    treeData.value = data || []
  } catch (error) {
    console.error('获取组织树形数据失败:', error)
    message.error(error||'获取组织树形数据失败')
  } finally {
    treeLoading.value = false
  }
}

// 获取指定组织下的所有班级ID
const getClassIds = (org: Organization): number[] => {
  const ids: number[] = []
  const traverse = (item: Organization) => {
    if (item.type === organizationType.CLASS) {
      ids.push(item.id)
    } else if (item.children?.length) {
      item.children.forEach(traverse)
    }
  }
  traverse(org)
  return ids
}

// 获取学生列表
const getStudentList = async () => {
  loading.value = true
  try {
    // 构建部门ID数组参数
    let departmentIds: number[] = []
    if (selectedNode.value?.key) {
      if (selectedNode.value.type === organizationType.CLASS) {
        // 班级直接使用ID
        departmentIds = [Number(selectedNode.value.key)]
      } else {
        // 学院或专业需要获取下属所有班级ID
        const org = treeData.value.find(item => 
          selectedNode.value.type === organizationType.COLLEGE 
            ? item.id === Number(selectedNode.value.key)
            : item.children?.some(major => major.id === Number(selectedNode.value.key))
        )
        if (org) {
          if (selectedNode.value.type === organizationType.COLLEGE) {
            departmentIds = getClassIds(org)
          } else {
            const major = org.children?.find(item => item.id === Number(selectedNode.value.key))
            if (major) {
              departmentIds = getClassIds(major)
            }
          }
        }
      }
    }

    const data = await studentApi.getStudentPage({
      departmentIds: departmentIds.join(','),  // 将数组转换为逗号分隔的字符串
      userCode: searchForm.value.studentNo,
      realName: searchForm.value.name,
      page: pagination.value.current - 1,
      size: pagination.value.pageSize
    })
    
    tableData.value = data.content
    pagination.value.total = data.totalElements
  } catch (error) {
    console.error('获取学生列表失败:', error)
    message.error(error||'获取学生列表失败')
  } finally {
    loading.value = false
  }
}

// 处理表格变化
const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  getStudentList()
}

// 处理搜索
const handleSearch = () => {
  pagination.value.current = 1
  getStudentList()
}

// 处理重置
const handleReset = () => {
  searchForm.value = {}
  pagination.value.current = 1
  getStudentList()
}

// 监听选中节点变化
watch(() => selectedNode.value?.key, (newVal) => {
  if (newVal) {
    pagination.value.current = 1
    getStudentList()
  } else {
    tableData.value = []
  }
})

// 新增学生
const handleAdd = () => {
  if (!selectedNode.value || selectedNode.value.type === organizationType.COLLEGE || selectedNode.value.type === organizationType.MAJOR) {
    message.warning('请选择班级')
    return
  }
  formState.value = {
    realName: '',
    userCode: '',
    gender: 0, // 默认未知
    phone: '',
    email: '',
    departmentId: selectedNode.value.key
  }
  modalTitle.value = '新增学生'
  modalVisible.value = true
}

// 编辑学生
const handleEdit = async (record: any) => {
  try {
    // 获取最新的学生详情
    const studentInfo = await studentApi.getById(record.id)
    
    // 填充表单数据
    formState.value = {
      id: studentInfo.id,
      userCode: studentInfo.username,
      realName: studentInfo.realName,
      gender: studentInfo.gender || 0, // 如果没有性别信息则默认为未知
      phone: studentInfo.phone || '',
      email: studentInfo.email || '',
      departmentId: studentInfo.departmentId
    }
    modalTitle.value = '编辑学生'
    modalVisible.value = true
  } catch (error) {
    console.error('获取学生详情失败:', error)
    message.error(error||'获取学生详情失败')
  }
}

// 更新学生状态
const handleStatusChange = (record: Student) => {
  Modal.confirm({
    title: '确认操作',
    content: `确定要${record.status ? '禁用' : '启用'}学生"${record.realName}"吗？`,
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      try {
        await studentApi.updateStatus(record.id, !record.status)
        message.success('操作成功')
        getStudentList()
      } catch (error) {
        console.error('操作失败:', error)
        message.error(error||'操作失败')
      }
    }
  })
}

// 重置密码
const handleResetPassword = (record: Student) => {
  Modal.confirm({
    title: '确认重置密码',
    content: `确定要重置学生"${record.realName}"的密码吗？重置后密码将变为学号。`,
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      try {
        await studentApi.resetPassword(record.id)
        message.success('密码重置成功')
      } catch (error) {
        console.error('密码重置失败:', error)
        message.error(error||'密码重置失败')
      }
    }
  })
}

// 删除学生
const handleDelete = (record: Student) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除学生"${record.realName}"吗？`,
    okText: '确认',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        await studentApi.delete(record.id)
        message.success('删除成功')
        getStudentList()
      } catch (error) {
        console.error('删除失败:', error)
        message.error(error||'删除失败')
      }
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    modalLoading.value = true
    
    if (formState.value.id) {
      // 更新时的参数适配
      const updateData = {
        userCode: formState.value.userCode,
        realName: formState.value.realName,
        gender: formState.value.gender,
        phone: formState.value.phone,
        email: formState.value.email,
        departmentId: formState.value.departmentId
      }
      await studentApi.update(formState.value.id, updateData)
      message.success('更新成功')
    } else {
      // 创建时的参数适配
      const createData = {
        userCode: formState.value.userCode,
        realName: formState.value.realName,
        gender: formState.value.gender,
        phone: formState.value.phone,
        email: formState.value.email,
        departmentId: formState.value.departmentId
      }
      await studentApi.create(createData)
      message.success('创建成功')
    }
    
    modalVisible.value = false
    getStudentList()
  } catch (error) {
    console.error('提交失败:', error)
    message.error(error||'提交失败')
  } finally {
    modalLoading.value = false
  }
}

// 表单验证规则
const formRules = {
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  userCode: [
    { required: true, message: '请输入学号', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { 
      pattern: /^1[3-9]\d{9}$/, 
      message: '请输入正确的手机号', 
      trigger: 'blur',
      transform: (value: string) => value?.trim()
    }
  ],
  email: [
    { 
      type: 'email', 
      message: '请输入正确的邮箱地址', 
      trigger: 'blur',
      transform: (value: string) => value?.trim()
    }
  ]
}

// 添加选中节点处理函数
const handleSelect = (selectedKeys: Key[], { node }: any) => {
  if (selectedKeys.length === 0) {
    selectedNode.value = null
    tableData.value = []
    return
  }
  
  selectedNode.value = {
    key: node.key,
    type: node.type,
    title: node.title
  }
  
  // 重置分页并查询
  pagination.value.current = 1
  getStudentList()
}

// 初始化
onMounted(() => {
  getOrganizationTree()
  getStudentList()
})
</script>

<template>
  <div class="student-page">
    <div class="page-container">
      <!-- 左侧组织树 -->
      <Card class="tree-card" :loading="treeLoading">
        <template #title>组织架构</template>
        <Tree
          v-if="!treeLoading"
          :tree-data="treeNodes"
          :show-icon="true"
          :default-expand-all="true"
          @select="handleSelect"
        />
      </Card>

      <!-- 右侧学生列表 -->
      <Card class="content-card">
        <template #title>学生列表</template>
        <template #extra>
          <Button
            type="primary"
            :disabled="!selectedNode || selectedNode.type === organizationType.COLLEGE || selectedNode.type === organizationType.MAJOR"
            @click="handleAdd"
          >
            <template #icon><PlusOutlined /></template>
            新增学生
          </Button>
        </template>

        <!-- 添加搜索表单 -->
        <Form layout="inline" class="search-form">
          <Form.Item label="学号">
            <Input
              v-model:value="searchForm.studentNo"
              placeholder="请输入学号"
              allow-clear
              @keyup.enter="handleSearch"
            />
          </Form.Item>
          <Form.Item label="姓名">
            <Input
              v-model:value="searchForm.name"
              placeholder="请输入姓名"
              allow-clear
              @keyup.enter="handleSearch"
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" @click="handleSearch">
                <template #icon><SearchOutlined /></template>
                查询
              </Button>
              <Button @click="handleReset">
                <template #icon><ReloadOutlined /></template>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          :loading="loading"
          :columns="columns"
          :data-source="tableData"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <template #action="{ record }">
            <Space>
              <Button type="link" @click="handleEdit(record)">
                <template #icon><EditOutlined /></template>
                编辑
              </Button>
              <Button type="link" @click="handleResetPassword(record)">
                <template #icon><KeyOutlined /></template>
                重置密码
              </Button>
              <Button type="link" danger @click="handleDelete(record)">
                <template #icon><DeleteOutlined /></template>
                删除
              </Button>
            </Space>
          </template>
        </Table>
      </Card>
    </div>

    <!-- 新增/编辑弹窗 -->
    <Modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :maskClosable="false"
      :confirmLoading="modalLoading"
      okText="确认"
      cancelText="取消"
      @ok="handleSubmit"
    >
      <Form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <Form.Item label="姓名" name="realName">
          <Input v-model:value="formState.realName" placeholder="请输入姓名" />
        </Form.Item>
        <Form.Item label="学号" name="userCode">
          <Input v-model:value="formState.userCode" placeholder="请输入学号" />
        </Form.Item>
        <Form.Item label="性别" name="gender">
          <Select
            v-model:value="formState.gender"
            placeholder="请选择性别"
            :options="genderOptions"
          />
        </Form.Item>
        <Form.Item label="手机号" name="phone">
          <Input 
            v-model:value="formState.phone" 
            placeholder="请输入手机号"
            @blur="e => formState.phone = e.target.value.trim()"
          />
        </Form.Item>
        <Form.Item label="邮箱" name="email">
          <Input 
            v-model:value="formState.email" 
            placeholder="请输入邮箱"
            @blur="e => formState.email = e.target.value.trim()"
          />
        </Form.Item>
      </Form>
    </Modal>

    <!-- 其他确认弹窗也需要修改按钮文本 -->
    <Modal
      v-model:visible="deleteModalVisible"
      title="确认删除"
      :maskClosable="false"
      okType="danger"
      okText="确认"
      cancelText="取消"
      @ok="handleDeleteConfirm"
    >
      <p>确定要删除该学生吗？</p>
    </Modal>

    <Modal
      v-model:visible="resetPasswordModalVisible"
      title="确认重置密码"
      :maskClosable="false"
      okText="确认"
      cancelText="取消"
      @ok="handleResetPasswordConfirm"
    >
      <p>确定要重置该学生的密码吗？重置后密码将变为学号。</p>
    </Modal>
  </div>
</template>

<style lang="less" scoped>
.student-page {
  .page-container {
    display: flex;
    gap: 16px;
    height: 100%;

    .tree-card {
      width: 280px;
      :deep(.ant-card-body) {
        padding: 0;
      }
    }

    .content-card {
      flex: 1;
    }
  }

  .search-form {
    margin-bottom: 24px;
    padding: 24px;
    background: #fafafa;
    border-radius: 2px;
  }

  :deep(.ant-tag) {
    &[role="button"] {
      cursor: pointer;
      
      &:hover {
        opacity: 0.8;
      }
    }
  }
}
</style> 